<template>
  <div class="brand-management">
    <!-- 统计卡片 -->
    <lay-card>
      <div class="stats-cards">
        <lay-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ stats.total }}</div>
            <div class="stats-label">总品牌数</div>
          </div>
        </lay-card>
        <lay-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ stats.show }}</div>
            <div class="stats-label">显示中</div>
          </div>
        </lay-card>
        <lay-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ stats.hide }}</div>
            <div class="stats-label">已隐藏</div>
          </div>
        </lay-card>
        <lay-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ stats.countries }}</div>
            <div class="stats-label">涉及国家</div>
          </div>
        </lay-card>
      </div>
    </lay-card>

    <!-- 操作区域 -->
    <lay-card style="margin-top: 16px;">
      <div class="toolbar">
        <div class="toolbar-left">
          <lay-button type="primary" @click="handleAdd">
            <lay-icon type="layui-icon-add-1"></lay-icon>
            新增品牌
          </lay-button>
          <lay-button 
            type="danger" 
            :disabled="selectedRowKeys.length === 0"
            @click="handleBatchDelete"
          >
            <lay-icon type="layui-icon-delete"></lay-icon>
            批量删除
          </lay-button>
          <lay-button @click="handleRefresh">
            <lay-icon type="layui-icon-refresh"></lay-icon>
            刷新
          </lay-button>
        </div>
        <div class="toolbar-right">
          <lay-input 
            v-model="searchForm.keyword" 
            placeholder="搜索品牌名称"
            style="width: 200px; margin-right: 10px;"
            @keyup.enter="handleSearch"
          >
            <template #suffix>
              <lay-icon type="layui-icon-search" @click="handleSearch"></lay-icon>
            </template>
          </lay-input>
          <lay-select 
            v-model="searchForm.isShow" 
            placeholder="显示状态"
            style="width: 120px;"
            @change="handleSearch"
          >
            <lay-select-option value="">全部</lay-select-option>
            <lay-select-option :value="1">显示</lay-select-option>
            <lay-select-option :value="0">隐藏</lay-select-option>
          </lay-select>
        </div>
      </div>
    </lay-card>

    <!-- 品牌表格 -->
    <lay-card style="margin-top: 15px;">
      <lay-table 
        :columns="columns" 
        :data-source="tableData"
        :loading="loading"
        v-model:selectedKeys="selectedRowKeys"
        :default-toolbar="true"
        :pagination="false"
      >
        <template #logo="{ row }">
          <div class="brand-logo">
            <img v-if="row.logo" :src="row.logo" :alt="row.name" />
            <span v-else class="no-logo">暂无Logo</span>
          </div>
        </template>
        
        <template #name="{ row }">
          <div class="brand-name">
            <div class="chinese-name">{{ row.name }}</div>
          </div>
        </template>

        <template #isShow="{ row }">
          <lay-switch 
            v-model="row.isShow" 
            :value="1"
            :unvalue="0"
            @change="handleStatusChange(row)"
          ></lay-switch>
        </template>

        <template #action="{ row }">
          <lay-button size="xs" @click="handleEdit(row)">编辑</lay-button>
          <lay-button size="xs" type="danger" @click="handleDelete(row)">删除</lay-button>
        </template>
      </lay-table>

      <!-- 分页组件 -->
      <div class="pagination-wrapper">
        <lay-page 
          v-model="pagination.current"
          :total="pagination.total"
          :limit="pagination.pageSize"
          :show-count="true"
          :show-page="true"
          :show-limit="true"
          :show-skip="true"
          @change="handlePageChange"
          @limit="handlePageSizeChange"
        ></lay-page>
      </div>
    </lay-card>

    <!-- 品牌弹窗 -->
    <BrandDialog 
      v-model:visible="dialogVisible"
      :brand-data="currentBrand"
      :mode="dialogMode"
      @success="handleDialogSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { layer } from '@layui/layui-vue'
import BrandDialog from './components/BrandDialog.vue'
import { brandApi } from '../../../api/module/brand'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const dialogMode = ref<'add' | 'edit'>('add')
const currentBrand = ref<any>(null)
const selectedRowKeys = ref<string[]>([])

// 统计数据
const stats = reactive({
  total: 0,
  show: 0,
  hide: 0,
  countries: 0
})

// 搜索表单
const searchForm = reactive({
  keyword: '',
  isShow: ''
})

// 分页数据
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref<any[]>([])

// 表格列配置
const columns = [
  {
    title: '品牌Logo',
    key: 'logo',
    customSlot: 'logo',
    width: '100px'
  },
  {
    title: '品牌名称',
    key: 'name',
    customSlot: 'name',
    width: '200px'
  },
  {
    title: '官网',
    key: 'website',
    width: '200px'
  },
  {
    title: '排序',
    key: 'sortOrder',
    width: '80px'
  },
  {
    title: '状态',
    key: 'isShow',
    customSlot: 'isShow',
    width: '80px'
  },
  {
    title: '创建时间',
    key: 'createdAt',
    width: '180px'
  },
  {
    title: '操作',
    key: 'action',
    customSlot: 'action',
    width: '150px',
    fixed: 'right'
  }
]

// 获取品牌列表
const getBrandList = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword,
      isShow: searchForm.isShow
    }
    
    const response = await brandApi.getBrandList(params)
    if (response.code === 200) {
      tableData.value = response.data.list
      pagination.total = response.data.total
    }
  } catch (error) {
    layer.msg('获取品牌列表失败', { icon: 2 })
  } finally {
    loading.value = false
  }
}

// 获取统计数据
const getStats = async () => {
  try {
    const response = await brandApi.getBrandStats()
    if (response.code === 200) {
      Object.assign(stats, response.data)
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 处理新增
const handleAdd = () => {
  dialogMode.value = 'add'
  currentBrand.value = null
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row: any) => {
  dialogMode.value = 'edit'
  currentBrand.value = { ...row }
  dialogVisible.value = true
}

// 处理删除
const handleDelete = (row: any) => {
  layer.confirm(`确定要删除品牌"${row.name}"吗？`, {
    icon: 3,
    title: '删除确认'
  }, async () => {
    try {
      const response = await brandApi.deleteBrand(row.id)
      if (response.code === 200) {
        layer.msg('删除成功', { icon: 1 })
        getBrandList()
        getStats()
      }
    } catch (error) {
      layer.msg('删除失败', { icon: 2 })
    }
  })
}

// 处理批量删除
const handleBatchDelete = () => {
  if (selectedRowKeys.value.length === 0) {
    layer.msg('请选择要删除的品牌', { icon: 3 })
    return
  }

  layer.confirm(`确定要删除选中的 ${selectedRowKeys.value.length} 个品牌吗？`, {
    icon: 3,
    title: '批量删除确认'
  }, async () => {
    try {
      const response = await brandApi.batchDeleteBrands(selectedRowKeys.value)
      if (response.code === 200) {
        layer.msg('批量删除成功', { icon: 1 })
        selectedRowKeys.value = []
        getBrandList()
        getStats()
      }
    } catch (error) {
      layer.msg('批量删除失败', { icon: 2 })
    }
  })
}

// 处理状态变更
const handleStatusChange = async (row: any) => {
  try {
    const response = await brandApi.updateBrandStatus(row.id, row.isShow)
    if (response.code === 200) {
      layer.msg('状态更新成功', { icon: 1 })
      getStats()
    }
  } catch (error) {
    layer.msg('状态更新失败', { icon: 2 })
    // 恢复原状态
    row.isShow = row.isShow === 1 ? 0 : 1
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.current = 1
  getBrandList()
}

// 处理刷新
const handleRefresh = () => {
  searchForm.keyword = ''
  searchForm.isShow = ''
  pagination.current = 1
  getBrandList()
  getStats()
}

// 处理分页变化
const handlePageChange = (page: number) => {
  pagination.current = page
  getBrandList()
}

// 处理页大小变化
const handlePageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize
  pagination.current = 1
  getBrandList()
}

// 处理弹窗成功
const handleDialogSuccess = () => {
  getBrandList()
  getStats()
}

// 获取国家颜色
const getCountryColor = (country: string) => {
  const colorMap: Record<string, string> = {
    '中国': 'red',
    '美国': 'blue',
    '日本': 'orange',
    '德国': 'green',
    '韩国': 'purple'
  }
  return colorMap[country] || 'gray'
}

// 组件挂载时获取数据
onMounted(() => {
  getBrandList()
  getStats()
})
</script>

<style scoped>
.brand-management {
  padding: 0;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 0;
}

.stats-card {
  text-align: center;
  border: 1px solid #f0f0f0;
  transition: all 0.3s ease;
}

.stats-card:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stats-content {
  padding: 20px;
}

.stats-number {
  font-size: 28px;
  font-weight: bold;
  color: #1890ff;
  margin-bottom: 8px;
}

.stats-label {
  font-size: 14px;
  color: #666;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.toolbar-left {
  display: flex;
  gap: 8px;
}

.toolbar-right {
  display: flex;
  align-items: center;
}

.brand-logo {
  display: flex;
  align-items: center;
  justify-content: center;
}

.brand-logo img {
  width: 40px;
  height: 40px;
  object-fit: contain;
  border-radius: 4px;
}

.no-logo {
  color: #999;
  font-size: 12px;
}

.brand-name .chinese-name {
  font-weight: bold;
  margin-bottom: 2px;
}

.brand-name .english-name {
  font-size: 12px;
  color: #666;
}

.pagination-wrapper {
  margin-top: 16px;
  text-align: right;
}
</style>